<style>
.image {
  width: 100%;
  display: block;
}
</style>
<template>
	<div id="suggest_approve">
		<!--工具条-->
		<div name="searchColums">
			<el-form :inline="true"
			         :model="filters"
			         size="small"
			         ref="filters"
			         class="searchForm">
        <el-form-item class="el-form-item"
                      label="所属小区">
          <el-select size="small" v-model="filters.communityId" placeholder="请选择">
            <el-option v-for="item in communityOptions" :key="item.value" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
				<el-form-item class="el-form-item"
				              label="标题">
				<el-input  class="filter-item" placeholder="输入标题" v-model="filters.title"></el-input>
				</el-form-item>

				<span class="bth_search">
					<el-form-item>
						<el-button type="success"
						           icon="el-icon-search"
						           v-on:click="getDataGrid(true)">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button icon="el-icon-refresh"
						           @click="resetSearchForm('filters')">重置</el-button>
					</el-form-item>
				</span>
			</el-form>
		</div>
		<!--toolbar-->
		<el-row id="toolbar_unit">
			<el-col :span="24">
				<div class="grid-content bg-purple-light">
					<el-button type="success"
					           size="mini"
					           icon="el-icon-check"
					           @click="handleAdd">新增</el-button>
				</div>
			</el-col>
		</el-row>

		<!--列表-->
		<el-table :data="gridDatas"
		          id="dataGrid"
		          empty-text=" "
		          border
		          stripe
		          size="mini"
		          :header-row-class-name="headStyle"
		          highlight-current-row
		          v-loading="listLoading"
		          :row-class-name="tableRowClassName"
		          @sort-change="handleSortChange"
		          @selection-change="selsChange"
		          style="width: 100%;">
			<el-table-column type="selection"
			                 width="45"></el-table-column>
			<el-table-column prop="index"
			                 :formatter="index_formatter"
			                 label="序号"
			                 width="60"></el-table-column>
			<el-table-column prop="title"
			                 label="标题"
			                 width="180"
			                 show-overflow-tooltip></el-table-column>
			<el-table-column prop="communityName"
			                 label="小区名称"
			                 width="180"
			                 show-overflow-tooltip></el-table-column>
			<el-table-column prop="createBy"
			                 label="创建人"
			                 show-overflow-tooltip></el-table-column>
			<!--<el-table-column label="附件"
			                 width="100">
				<template slot-scope="scope">
					<el-button round
					           @click="showImgPath(scope.$index, scope.row)">查看</el-button>
				</template>
			</el-table-column>-->
			<el-table-column label="操作" fixed="right">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24"
		        class="toolbar"
		        id="pageDiv">
			<el-pagination small
			               background
			               @current-change="handleCurrentChange"
			               @size-change="handleSizeChange"
			               :page-sizes="[10, 20, 50, 100]"
			               :page-size="pageSize"
			               :total="total"
			               layout="total,sizes, prev, pager, next"
			               style="float:right;"></el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑"
		           :visible.sync="editFormVisible"
		           :close-on-click-modal="false">
			<el-form :model="editForm"
               label-width="80px"
               :rules="addFormRules"
               ref="editForm"
               size="medium">
				<el-col :span="12">
					<el-form-item label="所属小区"
					              prop="communityId">
            <el-select size="small" v-model="editForm.communityId" clearable placeholder="请选择">
              <el-option v-for="item in communityOptions" :key="item.value" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="标题"
					              prop="title">
						<el-input v-model="editForm.title" size="small"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="上传图片"
					              prop="imgPath">
            <el-input v-model="editForm.imgPath"
                      type="hidden"
                      style="display: none!important;"></el-input>
						<el-upload class="upload-demo"
                       action="/admin/repairRecord/upload"
                       :data="uploadParams"
                       :on-preview="imgHandlePreview"
                       :on-remove="imgHandleRemove"
                       :before-upload="beforeImgUpload"
                       :file-list="imgList"
                       :on-success="imgSuccess"
                       :headers="uploadHeader"
                       list-type="picture">
							<el-button size="small"
							           type="primary">上传</el-button>
							<div slot="tip"
							     class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
						</el-upload>
					</el-form-item>
				</el-col>

			</el-form>
			<div slot="footer"
			     class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary"
				           @click.native="editSubmit"
				           :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增"
		           :visible.sync="addFormVisible"
		           :close-on-click-modal="false"
		           @close="handleAddBeforeClose('addForm')">
			<el-form :model="addForm"
               label-width="80px"
               :rules="addFormRules"
               ref="addForm"
               size="medium">
        <el-col :span="12">
          <el-form-item label="所属小区" prop="communityId">
            <el-select size="small" v-model="addForm.communityId" clearable placeholder="请选择">
              <el-option v-for="item in communityOptions" :key="item.value" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
				<el-col :span="12">
					<el-form-item label="标题"
					              prop="title">
						<el-input v-model="addForm.title" size="small"></el-input>
					</el-form-item>
				</el-col>
				<el-input v-model="addForm.id"
				          type="hidden"
				          style="display: none!important;"></el-input>
				<el-col :span="24">
					<el-form-item label="附件"
					              prop="imgPath">
						<el-upload class="upload-demo"
						           action="/admin/repairRecord/upload"
						           :on-preview="imgHandlePreview"
						           :on-remove="imgHandleRemove"
						           :before-upload="beforeImgUpload"
						           :file-list="imgList"
						           :on-success="imgSuccess"
						           :headers="uploadHeader"
                       :data="uploadParams"
						           list-type="picture">
							<el-button size="small"
							           type="primary">上传</el-button>
							<div slot="tip"
							     class="el-upload__tip">只能上传图片</div>
						</el-upload>
					</el-form-item>
				</el-col>

			</el-form>
			<div slot="footer"
			     class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary"
				           @click.native="addSubmit"
				           :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--图片查看界面-->
		<el-dialog title="附件查看"
		           :visible.sync="imgFormVisible"
		           :close-on-click-modal="false">
			<el-row>
				<el-col v-for="(imgPath,index) in imgListShow"
				        :key="index">
					<el-card :body-style="{ padding: '0px' }">
						<img :src="imgPath.data"
						     class="image" />
					</el-card>

				</el-col>
			</el-row>
		</el-dialog>
	</div>
</template>
<script>
import { getToken, setToken, removeToken,getFileIp } from "@/util/auth";
import { getUUID } from "@/util/util";
import request from "@/router/axios";
export default {
  name: "appShowMessage",
  data() {
    return {
      communityOptions: [],
      filters: {
        communityId: "",
        title: ""
      },
      url: {
        //单元数据
        list: "/admin/appMessageShow/page",
        save: "/admin/appMessageShow/add",
        edit: "/admin/appMessageShow/edit",
        approve: "/admin/appMessageShow/approve",
        submitSug: "/admin/appMessageShow/fenpei",
        del: "/admin/appMessageShow/delete"
      },
      gridDatas: [],
      suggestTypeOptions: [],
      sort: {
        sort: "sort",
        order: "asc"
      },
      total: 0,
      page: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],
      imgPaths: [],
      imgList: [],
      imgListShow: [],
      editLoading: false,
      editFormVisible: false,
      addFormVisible: false,
      editForm: {},
      uploadParams: {type: 'applbt',relationId:""},
      addForm: {},
      editFormRules: {},
      addFormRules: {},
      userSelectFormVisible: false,
      imgFormVisible: false,
      userSelectLoading: false,
      userSelectForm: {},
      uploadHeader: {
        Authorization: "Bearer " + getToken()
      }
    };
  },
  methods: {
    //初始化数据字典
    initDictsData: function () {
      request.get("/admin/community?getCommunitysByCurrentUser").then((res) => {
        if (res.status === 200) {
          this.communityOptions = res.data;
        }
      });
    },
    handleSortChange(sort) {
      this.sort = {
        sort: sort.prop,
        order: sort.order == "ascending" ? "asc" : "desc"
      };
      this.getDataGrid();
    },
    tableRowClassName(row, index) {
      //把每一行的索引放进row
      row.index = row.rowIndex;
    },
    headStyle({ row, rowIndex }) {
      return "table_head_style";
    },
    index_formatter: function(row, column, cellValue, index) {
      //放回索引值
      return this.pageSize * (this.page - 1) + 1 + index;
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getDataGrid();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.page = 1;
      this.getDataGrid();
    },
    resetSearchForm(formName) {
      this.filters = {
        title: '',
        communityId: ''
      }
    },
    selsChange: function(sels) {
      this.sels = sels;
    },
    handleSubmit: function(index, row) {
      this.editUnitFormVisible = true;
      this.editUnitForm = Object.assign({}, row);
    },
    //图片点击事件
    imgHandlePreview: function(file) {},
    //图片删除事件
    imgHandleRemove: function(file, fileList) {
    	let para = {
          id: file.id
        };
        request.get("/admin/repairRecord/deleteImg", {
          params: para
        }).then((res) => {
          this.listLoading = false;
        });
    },
    //图片上传之前验证格式
    beforeImgUpload: function(file) {
      const type = file.type;
      const flag =
        type == "image/jpeg" ||
        type == "image/gif" ||
        type == "image/png" ||
        type == "image/bmp";
      if (!flag) {
        this.$message.error("只支持上传图片!");
      }

      return flag;
    },
    //图片上传成功后
    imgSuccess: function(response, file, fileList) {
    	var fileId = response.obj;
      for(var i=0;i<fileList.length;i++){
      	if(file.uid==fileList[i].uid){
      		fileList[i].id=fileId;
      		break;
      	}
      }
    },
    showImgPath: function(index, row) {
      this.imgListShow = [];
      let para = { id: row.id };
        request({
          url: "/admin/repairRecord/showImg",
          method: "get",
          params: para
        }).then(res => {
        	for (var i = 0; i < res.data.length; i++) {
	          var img = {}
	          img.id = res.data[i].id
	          img.data = getFileIp() + res.data[i].data
	          this.imgListShow.push(img)
        	}

        });
      this.imgFormVisible = true;
    },

    //新增
    handleAdd: function() {
      this.imgList = [];
      var zj = getUUID();
      this.addForm.id = zj;
      this.uploadParams.relationId = zj
      this.addFormVisible = true;
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let para = {
          id: row.id
        };
        request.get(this.url.del, {
          params: para
        }).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1500
          });
          this.getDataGrid();
        });
      }).catch(() => {

      });
    },
    //显示编辑界面
		handleEdit: function(index, row) {
			this.editFormVisible = true;
			this.editForm = Object.assign({}, row);
			this.imgList = [];
			this.uploadParams.relationId = row.id ;
      let para = { id: row.id };
        request({
          url: "/admin/repairRecord/showImg",
          method: "get",
          params: para
        }).then(res => {
        	for(var i=0;i<res.data.length;i++){
        		this.imgList.push({url:getFileIp() + res.data[i].data,id:res.data[i].id});
        	}

        });

		},
		handleAddBeforeClose(form){
				const set = this.$refs;
				set[form].resetFields();
			},

    //编辑
    editSubmit: function() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let para = Object.assign({}, this.editForm);
            request.post(this.url.edit, para).then(res => {
            	if(!res.data.data){
            		  this.editLoading = false;
		              this.$message({
		                message: res.data.msg,
		                type: "info",
		                duration: 1500
		              });
		              return;
            	}
              this.editLoading = false;
              this.$message({
                message: "提交成功",
                type: "success",
                duration: 1500
              });
              this.$refs["editForm"].resetFields();
              this.editFormVisible = false;
              this.getDataGrid();
            });
          });
        }
      });
    },
    addSubmit: function() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            this.addForm.imgPath = this.imgPaths.toString();
            let param = Object.assign({}, this.addForm);
            request.post(this.url.save, param).then(res => {
            	if(!res.data.data){
            		  this.editLoading = false;
		              this.$message({
		                message: res.data.msg,
		                type: "info",
		                duration: 1500
		              });
		              return;
            	}
              this.editLoading = false;
              this.$message({
                message: "提交成功",
                type: "success",
                duration: 1500
              });
              this.$refs["addForm"].resetFields();
              this.addFormVisible = false;
              this.getDataGrid();
            });
          });
        }
      });
    },

    //获取单元列表数据
    getDataGrid(flag) {
      //获取当前树节点选中小区
      if(flag){
      	this.page = 1;
      }
      let para = {
        params: {
          page: this.page,
          limit: this.pageSize,
          //排序
          orderByField: this.sort.sort,
          isAsc: this.sort.order,
          communityId: this.filters.communityId,
          title: this.filters.title
        }
      };
      this.listLoading = true;
      request.get(this.url.list, para).then(res => {
        this.total = res.data.total;
        var datas = res.data.records;
        this.gridDatas = datas;
        this.listLoading = false;
      });
    }
  },
  mounted() {
    this.initDictsData();
    this.getDataGrid();
  }
};
</script>
